package collections.queue;

import org.junit.Test;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @Author: ycy
 * @CreateDate: 2019/4/9 14:11
 */
public class queue {

  public void test() {
    ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue(2);
  }

  public static void main(String[] args) {
    //队列 offer、poll
    Queue<String> queue = new LinkedList<String>();

    //添加元素
    queue.offer("a");
    queue.offer("b");
    queue.offer("c");
    queue.offer("d");
    queue.offer("e");
    for (String q : queue) {
      System.out.println(q);
    }
    System.out.println("===");
    System.out.println("poll=" + queue.poll()); //返回第一个元素，并在队列中删除
    for (String q : queue) {
      System.out.println(q);
    }
    System.out.println("===");
    System.out.println("element=" + queue.element()); //返回第一个元素
    for (String q : queue) {
      System.out.println(q);
    }
    System.out.println("===");
    System.out.println("peek=" + queue.peek()); //返回第一个元素
    for (String q : queue) {
      System.out.println(q);
    }
    while(true){

    }
  }

  @Test
  public void delayqueue() {
    DelayQueue<EleDelayed> queue = new DelayQueue<EleDelayed>();
    EleDelayed ele1 = new EleDelayed(1, 10);
    queue.offer(ele1);

    // 非阻塞方法
    EleDelayed poll = queue.poll();
    System.out.println(poll);

    try {
      //阻塞方法
      EleDelayed take = queue.take();
      System.out.println(take);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

  }

  class EleDelayed implements Delayed {

    int value;

    long unit;

    EleDelayed(int value, long unit) {
      this.value = value;
      this.unit = unit;
    }

    @Override
    public long getDelay(TimeUnit unit) {
      return this.unit;
    }

    @Override
    public int compareTo(Delayed o) {
      return 0;
    }

    @Override
    public String toString() {
      return "EleDelayed{" +
              "value=" + value +
              ", unit=" + unit +
              '}';
    }
  }

}
